package initialize

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"go.uber.org/zap"

	"yanxue_ai_go/pkg/common/config"
	"yanxue_ai_go/pkg/common/logger"
)

// ServerConfig HTTP服务器配置
type ServerConfig struct {
	Port         int
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
	IdleTimeout  time.Duration
}

// RunServer 运行HTTP服务器
func RunServer(serviceName string, handler http.Handler, cfg *config.Config) error {
	// 根据服务名确定端口
	port := getServicePort(serviceName, cfg)

	server := &http.Server{
		Addr:         fmt.Sprintf(":%d", port),
		Handler:      handler,
		ReadTimeout:  time.Duration(cfg.Server.ReadTimeout) * time.Second,
		WriteTimeout: time.Duration(cfg.Server.WriteTimeout) * time.Second,
		IdleTimeout:  time.Duration(cfg.Server.IdleTimeout) * time.Second,
	}

	// 启动服务器
	go func() {
		logger.Logger.Info("Service started",
			zap.String("service", serviceName),
			zap.String("addr", server.Addr),
			zap.String("env", cfg.App.Environment))

		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			logger.Logger.Fatal("Failed to start server", zap.Error(err))
		}
	}()

	// 等待中断信号
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	logger.Logger.Info("Shutting down service", zap.String("service", serviceName))

	// 优雅关闭
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	if err := server.Shutdown(ctx); err != nil {
		logger.Logger.Error("Server forced to shutdown", zap.Error(err))
		return err
	}

	logger.Logger.Info("Service stopped", zap.String("service", serviceName))
	return nil
}

// getServicePort 根据服务名获取端口
func getServicePort(serviceName string, cfg *config.Config) int {
	switch serviceName {
	case "gateway":
		return cfg.Server.Port // 通常是8080
	case "agent":
		return 8081
	case "mcp":
		return 8082
	case "rag":
		return 8083
	default:
		return cfg.Server.Port
	}
}

// GracefulShutdown 优雅关闭处理器
type GracefulShutdown struct {
	serviceName string
	server      *http.Server
	cleanup     func() error
}

// NewGracefulShutdown 创建优雅关闭处理器
func NewGracefulShutdown(serviceName string, server *http.Server, cleanup func() error) *GracefulShutdown {
	return &GracefulShutdown{
		serviceName: serviceName,
		server:      server,
		cleanup:     cleanup,
	}
}

// Wait 等待关闭信号并执行优雅关闭
func (gs *GracefulShutdown) Wait() error {
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	logger.Logger.Info("Shutting down service", zap.String("service", gs.serviceName))

	// 关闭HTTP服务器
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	var shutdownErr error
	if gs.server != nil {
		shutdownErr = gs.server.Shutdown(ctx)
	}

	// 执行清理操作
	var cleanupErr error
	if gs.cleanup != nil {
		cleanupErr = gs.cleanup()
	}

	// 返回第一个错误
	if shutdownErr != nil {
		logger.Logger.Error("Server shutdown error", zap.Error(shutdownErr))
		return shutdownErr
	}

	if cleanupErr != nil {
		logger.Logger.Error("Cleanup error", zap.Error(cleanupErr))
		return cleanupErr
	}

	logger.Logger.Info("Service stopped gracefully", zap.String("service", gs.serviceName))
	return nil
}
